//
//  ShopViewController.swift
//  iModern
//
//  Created by Ralf on 7/29/15.
//  Copyright (c) 2015 com.starlooking. All rights reserved.
//

import UIKit

class ShopViewController: TableViewController, UIActionSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate
{
    var contactType:   String?
    var quanImageView: UIImageView?
    var torf:   Bool?
    
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
        
        self.tableView.registerNib(UINib(nibName: "ShopViewAvatarCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "Avatar")
        self.tableView.registerNib(UINib(nibName: "ShowViewBillboardCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "Billboard")
        
        self.tableView.registerNib(UINib(nibName: "ShowViewRegisterCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "Register")
        self.tableView.registerNib(UINib(nibName: "ShopViewCreateAdvertisingCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "CreateAdvertising")
        self.tableView.registerNib(UINib(nibName: "ShopViewShopSettingCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "ShopSetting")
        self.tableView.registerNib(UINib(nibName: "ShopViewAdvertisingManagementCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "AdvertisingManagement")
        self.tableView.registerNib(UINib(nibName: "ShopViewAppointmentManagementCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "AppointmentManagement")
        
        //        self.tableView.separatorStyle = UITableViewCellSeparatorStyle.SingleLine
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "refresh:", name: "Refresh Shop", object: nil)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "refresh2:", name: "Refresh Shop2", object: nil)
        
        self.loadData()
    }
    
    override func viewWillAppear(animated: Bool)
    {
        super.viewWillAppear(animated);
        MobClick.beginLogPageView("ShopView")
        
        appDelegate.rootController.navigationItem.leftBarButtonItems = nil
        appDelegate.rootController.navigationItem.rightBarButtonItems = nil
        appDelegate.rootController.navigationItem.title = "匠铺"
    }
    
    override func viewWillDisappear(animated: Bool)
    {
        super.viewWillDisappear(animated);
        MobClick.endLogPageView("ShopView")
    }
    
    func loadData()
    {
        if appDelegate.isLogged()
        {
            contactType = appDelegate.contactManager.contact["type"] as? String
        }
    }
    
    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    //MARK:- tableViewDelegate
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
    {
        var height: CGFloat!
        
        if contactType == "Shop" && appDelegate.isLogged()
        {
            switch indexPath.row
            {
            case 0:
                return 150
            case 1:
                return 50
            case 2:
                return 50
            case 3:
                return 50
            default:
                return 50
            }
        }
        else
        {
            if indexPath.row == 0
            {
                height = 150
            }
            else
            {
                height = self.tableView.bounds.height - 150
            }
            
        }
        
        
        return height
    }
    
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int
    {
        return 1
        
    }
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        if contactType == "Shop" && appDelegate.isLogged()
        {
            return 5
        }
        else
        {
            return 2
        }
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        
        if contactType == "Shop" && appDelegate.isLogged()
        {
            var shopname: String?
            var address: String?
            //var imageURL: String?
            shopname = appDelegate.contactManager.contact["shopName"] as? String
            address = appDelegate.contactManager.contact["address"] as? String
            //imageURL = appDelegate.contactManager.contact["shopLogoURL"] as? String
            
            switch indexPath.row
            {
                
            case 0:
                let cell = tableView.dequeueReusableCellWithIdentifier("Register", forIndexPath: indexPath) as! ShowViewRegisterCell
                
                //                self.quanImageView = cell.headImageView
                if (self.quanImageView != nil)
                {
                    self.quanImageView = cell.headImageView
                }
                if address != nil || shopname != nil
                {
                    cell.setData(address!,shopName:shopname!)
                }
                return cell
                
            case 1:
                
                let cell = tableView.dequeueReusableCellWithIdentifier("CreateAdvertising", forIndexPath: indexPath) as! ShopViewCreateAdvertisingCell
                return cell
            case 2:
                
                let cell = tableView.dequeueReusableCellWithIdentifier("ShopSetting", forIndexPath: indexPath) as! ShopViewShopSettingCell
                return cell
                
            case 3:
                
                let cell = tableView.dequeueReusableCellWithIdentifier("AdvertisingManagement", forIndexPath: indexPath) as! ShopViewAdvertisingManagementCell
                return cell
                
            default:
                
                let cell = tableView.dequeueReusableCellWithIdentifier("AppointmentManagement", forIndexPath: indexPath) as! ShopViewAppointmentManagementCell
                return cell
                
            }
        }
        else
        {
            switch indexPath.row
            {
            case 0:
                
                let cell = tableView.dequeueReusableCellWithIdentifier("Avatar", forIndexPath: indexPath) as! ShopViewAvatarCell
                return cell
            default:
                
                let cell = tableView.dequeueReusableCellWithIdentifier("Billboard", forIndexPath: indexPath) as! ShowViewBillboardCell
                return cell
            }
        }
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {
        if contactType == "Shop" && appDelegate.isLogged()
        {
            
            switch indexPath.row
            {
            case 0:
                let alertContorller = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
                let alertCancel = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
                let alertCamera = UIAlertAction(title: "相机", style: UIAlertActionStyle.Default) {
                    (action: UIAlertAction!) -> Void in
                    self.takePhoto()
                }
                let alertLib = UIAlertAction(title: "相册", style: UIAlertActionStyle.Default){
                    (action:UIAlertAction!) -> Void in
                    self.choosePhotoFromLibrary()
                }
                alertContorller.addAction(alertCancel)
                alertContorller.addAction(alertCamera)
                alertContorller.addAction(alertLib)
                self.presentViewController(alertContorller, animated: true, completion: nil)
            case 1:
                let vc = CreateAdvertisingViewController()
                self.navigationController?.pushViewController(vc, animated: true)
            case 2:
                let vc = ShopManagementController()
                self.navigationController?.pushViewController(vc, animated: true)
            case 3:
                let vc = ShopAdvertisingViewController()
                self.navigationController?.pushViewController(vc, animated: true)
            default:
                let vc = ShopOrdersViewController()
                self.navigationController?.pushViewController(vc, animated: true)
                
            }
        }
        else
        {
            
        }
    }
    
    deinit
    {
        print("deinit")
    }
    
    @IBAction func refresh(sender: AnyObject)
    {
        self.loadData()
        tableView.reloadData()
    }
    
    @IBAction func refresh2(sender: AnyObject)
    {
        self.loadData()
        tableView.reloadData()
    }
    
    
    
    func takePhoto()
    {
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.allowsEditing = true
        imagePicker.sourceType = .Camera
        appDelegate.navigationController.presentViewController(imagePicker, animated: true)
            {
                
        }
    }
    
    func choosePhotoFromLibrary()
    {
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.allowsEditing = true
        imagePicker.sourceType = .PhotoLibrary
        
        appDelegate.navigationController.presentViewController(imagePicker, animated: true)
            {
                
        }
    }
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject:AnyObject]!)
    {
        
        let rs = appDelegate.contactManager.uploadShopLogo(image)
        
        if rs == nil
        {
            self.alertNetworkConnectionException()
        }
        
        if rs!.hasErrors()
        {
            if rs?.errorCode == 3020
            {
                alertUserStatusException()
                NSNotificationCenter.defaultCenter().postNotificationName("Logout", object: nil)
                self.view.endEditing(true)
                navigationController?.popToRootViewControllerAnimated(true)
            }
            alertErrorMessage(rs!.errorMessage)
            return
        }
        
        
        self.quanImageView?.image = image
        tableView.reloadData()
        appDelegate.navigationController.dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    
}
